package com.ada;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import java.io.IOException;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args ) throws IOException {

        RestClient restClient = RestClient.builder(
                new HttpHost("127.0.0.1", 9200)).build();

// Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

// And create the API client
        ElasticsearchClient client = new ElasticsearchClient(transport);


        System.out.println(client.count());

        Product product = new Product("bk-2", "City bike 11", 123.0);

        IndexResponse response = client.index(i -> i
                .index("products")
                .id(product.getSku())
                .document(product)
        );
        System.out.println(response.version());

        IndexRequest.Builder<Product> indexReqBuilder = new IndexRequest.Builder<>();
        indexReqBuilder.index("product");
        indexReqBuilder.id(product.getSku());
        indexReqBuilder.document(product);

        response = client.index(indexReqBuilder.build());
        System.out.println(response.version());

        SearchResponse<Product> search = client.search(s -> s
                        .index("products")
                        .query(q -> q
                                .term(t -> t
                                        .field("code")
                                        .value("bike")
                                )),
                Product.class);

        for (Hit<Product> hit: search.hits().hits()) {
            System.out.println(hit);
            //processProduct(hit.source());
        }


    }
}
